<?php

namespace app\admin\controller;

use app\model\Member;
use app\model\Openid;
use app\model\WithdrawMode;
use app\model\Wxpay;
use think\exception\ValidateException;
use app\model\Withdraw;
use app\model\Message;
use app\model\Agent;
use app\model\Technical;
use app\model\Store;
use app\model\MemberBankcard;
use app\model\Operatingcity;

class WithdrawController extends Base
{

    function getPath()
    {
        $path = input('post.path', '', 'serach_in');
        $tmppath = explode('/', $path);
        return $tmppath;
    }

    function index()
    {
        $uniacid = uniacid();
        $path = input('post.path');
        $mo = input('post.mo');
        $page = input('post.page', 1, 'intval');
        $keyword = input('post.keyword', '', 'serach_in');
        $query = Withdraw::where(['uniacid' => $uniacid]);

        $mo = $this->getPath()[2];
        if (!empty($mo)) {
            $query->where('mo', $mo);
        }

        if (!empty($this->sid)) {
            $query->where('sid', $this->sid);
        }
        if (!empty($this->ocid)) {
            $query->where('ocid', $this->ocid);
        }

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();

        foreach ($res['data'] as &$vo) {
            $vo['sid'] = Store::getTitle($vo['sid']);
            $vo['MemberBankcard'] = MemberBankcard::getbankcard($vo['bid']);
            // $vo['create_time'] = time_format($vo['create_time']);
            if ($vo['mo'] == 'agent') {
                $vo['username'] = Agent::getTitle($vo['uid']);
            } elseif ($vo['mo'] == 'technical') {
                $vo['username'] = Technical::getTitle($vo['uid']);
            } elseif ($vo['mo'] == 'store') {
                $vo['username'] = Store::getTitlebyuid($vo['uid']);
            } elseif ($vo['mo'] == 'balance') {
                $vo['username'] = Member::get_name($vo['uid']);
            }
            $vo['mode'] = WithdrawMode::getmode($vo['pay_way']);
        }

        $data['data'] = $res;

        return $this->json($data);
    }

    function listUpdate()
    {
        $data = only('id,is_recommand,status,sort');
        if (!$data['id']) throw new ValidateException('参数错误');
        Withdraw::update($data);

        return $this->json(['msg' => '操作成功']);
    }

    function getInfo()
    {
        $id = $this->request->post('id', '', 'serach_in');
        if (!$id) throw new ValidateException('参数错误');

        $data = Withdraw::find($id);
        if (!empty($data)) {
            $data = $data->toArray();
            $data['create_time'] = time_format($data['create_time']);
            if ($data['mo'] == 'agent') {
                $data['username'] = Agent::getTitle($data['uid']);
            } elseif ($data['mo'] == 'technical') {
                $data['username'] = Technical::getTitle($data['uid']);
            } elseif ($data['mo'] == 'store') {
                $data['username'] = Store::getTitlebyuid($data['uid']);
            } elseif ($data['mo'] == 'balance') {
                $data['username'] = Member::get_name($data['uid']);
            }

            $data['MemberBankcard'] = MemberBankcard::getbankcard($data['bid']);
            $data['mode'] = WithdrawMode::getmode($data['pay_way']);
        }

        return $this->json(['data' => $data]);
    }

    public function audit1()
    {
        $id = $this->request->post('id');

        $withdrawInfo = Withdraw::where(['id' => $id])->find();
        if ($withdrawInfo->pay_way == 'wxpay') {
            $mode = WithdrawMode::where(['code' => 'wxpay'])->find();
            if ($mode->pay_mode == 2) {
                if (empty($withdrawInfo->uid)) {
                    return $this->json(['errno' => 1, 'msg' => '微信自动打款失败，用户会员信息不存在']);
                }

                $openid = Openid::getOpenidbyuuid($withdrawInfo->uid);

                $desc = '提现';
                switch ($withdrawInfo->mo) {
                    case 'technical':
                        $desc = '师傅提现';
                        break;
                    case 'store':
                        $desc = '商家提现';
                        break;
                    case 'operatingcity':
                        $desc = '代理提现';
                        break;
                    case 'balance':
                        $desc = '余额提现';
                        break;
                    case 'commission':
                        $desc = '佣金提现';
                        break;
                }

                //todo 微信打款
                $result = Wxpay::toBalance([
                    'partner_trade_no' => $withdrawInfo->withdraw_sn,  //商户订单号
                    'openid' => $openid,
                    'amount' => round($withdrawInfo->actual_amounts, 2) * 100,
                    'desc' => $desc
                ]);

                if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
                    $msg = '支付失败(' . $result['return_msg'] . ')';
                    return ['errno' => 1, 'msg' => $msg, 'message' => $msg, 'data' => $result];
                }
            }
        }

        $data['id'] = $id;
        $data['update_time'] = time();
        $data['status'] = 1;

        try {
            Withdraw::update($data);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        return $this->json(['msg' => '结算成功']);
    }

    function delete()
    {
        $idx = $this->request->post('id', '', 'serach_in');
        if (!$idx) throw new ValidateException('参数错误');
        Withdraw::destroy(['id' => explode(',', $idx)], true);
        return $this->json(['msg' => '操作成功']);
    }


    function modes()
    {
        $data = WithdrawMode::select()->toArray();
        return $this->json(['data' => $data]);
    }

    function modeListUpdate()
    {
        $data = only('code,pay_mode,status');
        if (!$data['code']) throw new ValidateException('参数错误');
        WithdrawMode::where(['code' => $data['code']])->update($data);

        return $this->json(['msg' => '操作成功']);
    }

    function doRefuse()
    {
        $id = $this->request->post('id');
        $value = $this->request->post('value');
        $withdrawInfo = Withdraw::where(['id' => $id])->find();
        if ($withdrawInfo['status'] == 1 || $withdrawInfo['status'] == 0) {
            $mo = $withdrawInfo['mo'];
            $uid = $withdrawInfo['uid'];;
            $amounts = $withdrawInfo['amounts'];
            if ($mo == 'agent') {
                $model = new Agent;
            } elseif ($mo == 'technical') {
                $model = new Technical;
            } elseif ($mo == 'store') {
                $model = new Store;
            } elseif ($mo == 'operatingcity') {
                $model = new Operatingcity;
            } elseif ($mo == 'balance') {
                $model = new Member();
            }
            if ($mo == 'agent') {
                $model->where('uid', $uid)->inc('income', $amounts)->update();
            } elseif ($mo == 'technical' || $mo == 'store' || $mo == 'operatingcity') {
                $model->where('uuid', $uid)->inc('income', $amounts)->update();
            } elseif($mo == 'balance'){
                $model->where('id', $uid)->inc('balance', $amounts)->update();
            }
            Withdraw::where(['id' => $id])->update(['status' => -1, 'reason_for_refusal' => $value]);
            return $this->json(['msg' => '操作成功']);
        } else {
            throw new ValidateException('状态错误');
        }
    }
}
